'''
Created on Nov 28, 2010

@author: oabalbin

This scripts implements samtools calls. 
To the newest functions included in samtools and not
implemented in pysam yet

Because sometimes the samtools version supportted
by pysam is not the latest. At the time of wirting
this script is samtools 0.1.8, being the latest
samtools 0.1.10
'''

import subprocess

def sam2bam(ref_genome, paired_aligned_sam):
    '''
    time samtools import /exds/projects/alignment_indexes/gatk/hg19/bwa/hg19.fa 
    s_3_12_sequence.hg19.aln.sam s_3_12_sequence.hg19.aln.bam
    '''
    outfile_name=paired_aligned_sam.replace('.sam','.bam')
    args=['samtools','import',ref_genome, paired_aligned_sam]
    
    f = open(outfile_name, "w")
    retcode = subprocess.call(args, stdout=f)
    f.close
    
    return outfile_name

    
def remove_duplicates(paired_aligned_bam):
    '''
    time samtools rmdup s_3_12_sequence.hg19.aln.bam s_3_12_sequence.hg19.aln.rmdup.bam
    '''
    
    outfile_name=paired_aligned_bam.replace('.bam','.rmdup.bam')
    args=['samtools','rmdup',paired_aligned_bam, outfile_name]    
    retcode = subprocess.call(args)
    
    return outfile_name
    
def sort_bam_file(paired_aligned_bam):
    '''
    '''
    outfile_name=paired_aligned_bam.replace('.bam','.sorted')
    args=['samtools','sort',paired_aligned_bam, outfile_name]    
    retcode = subprocess.call(args)
    
    return outfile_name

def index_bam_file(paired_aligned_bam):
    '''
    '''
    outfile_name=paired_aligned_bam.replace('.bam','.bam.bai')
    args=['samtools','index',paired_aligned_bam, outfile_name]    

    args= [a.replace(',',';') for a in args]
    command = ",".join(args).replace(',',' ').replace(';',',')

    return command, outfile_name

def merge_bam_files(bam_file_list, merged_file_name):
    '''
    --r     Attach an RG tag to each alignment. The tag value is inferred from file names. 
    '''
    
    args=['samtools','merge','-r', merged_file_name]+bam_file_list
    args= [a.replace(',',';') for a in args]
    command = ",".join(args).replace(',',' ').replace(';',',')

    return command
